********************************************************************************
*** 	
*** Estimate variation in markup and then calculate share of profits in revenue
***
***
********************************************************************************

*========================*
* Set up the environment *
*========================*


capture program drop init_usa

init_usa  // define directories 


*========================================================*
* Calculate markup variation by year fixed effects       *
*========================================================*

local baseyear = $startyear
local outputvar y // use total value of shipment  


use $DataC/data_clean.dta, replace

destring id, replace

EstMarkupVariationMedian `outputvar' $inputvar year, base(`baseyear')  // see file below

use $OutR/ProfitShare_$markupmethod_$inputvar, replace

egen median_propXmarkup = median(propXmarkup)

gen median_markup = $median_ElastSubst/($median_ElastSubst-1)

gen p = median_propXmarkup/median_markup

CalcProfitShare year propXmarkup p   // see file below

save $OutR/ProfitShare_$markupmethod_$inputvar, replace



*========================================================*
* save as ado files        
*========================================================*
program EstMarkupVariationMedian, eclass

	cap program drop EstMarkupVariationMedian
	version 13
	tempvar inv_rev_share
	syntax varlist(min=3 numeric), BASEyear(integer) 
	tokenize `varlist'
	local rev `1'
	local inputvar `2'
	local year `3'
	
	preserve
	
		gen double `inv_rev_share'=`rev'/`inputvar'
		bysort year: egen propXmarkup = median(`inv_rev_share')
		collapse (mean) propXmarkup, by(`year') fast
		save $OutR/ProfitShare_$markupmethod_$inputvar, replace
	restore
end





program CalcProfitShare

	cap program drop CalcProfitShare

	syntax varlist(min=3 numeric)
	tokenize `varlist'
	local year `1'
	local propXmarkup `2'
	local proportion `3'

	gen markup = `propXmarkup'/`proportion'
	
	gen ElastSubst = markup/(markup - 1)
	
	gen ProfitShare = 1/ElastSubst
	
	sort `year'
	
end
	